package cn.wzvtcsoft.sys.service.impl;

import cn.wzvtcsoft.base.BaseServiceImpl;
import cn.wzvtcsoft.common.util.PageUtil;
import cn.wzvtcsoft.common.vo.PageQueryParam;
import cn.wzvtcsoft.sys.entity.User;
import cn.wzvtcsoft.sys.entity.UserRole;
import cn.wzvtcsoft.sys.repository.UserRepository;
import cn.wzvtcsoft.sys.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserRepository> implements UserService {

  @Override
  public Page<User> listByConditionAndPage(PageQueryParam<User> pageQueryParam) {
    User userParam = pageQueryParam.getEntityParam();
    Pageable pageable = PageUtil.initPage(pageQueryParam.getPageParam());

    Page<User> users = thisRepository.findAll(new Specification<User>() {
      @Override
      public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        Path<String> nameField = root.get("name");
        Path<String> mobileField = root.get("mobile");

        List<Predicate> list = new ArrayList<>();
        if (userParam != null) {
          if (!StringUtils.isEmpty(userParam.getNumber())) {
            list.add(criteriaBuilder.or(
                criteriaBuilder.like(nameField, "%" + userParam.getNumber() + "%"),
                criteriaBuilder.like(mobileField, "%" + userParam.getNumber() + "%")
            ));
          }
        }

        Predicate[] arr = new Predicate[list.size()];
        return criteriaBuilder.and(list.toArray(arr));
      }
    }, pageable);
    return users;
  }

  @Override
  protected void beforeInsertOrUpdate(User user) {
    for (UserRole userRole : user.getUserRoles()) {
      userRole.setParent(user);
    }
  }

}
